/**
 * Created by Administrator on 2016/10/16.
 */
var express = require("express");
var router = express.Router();
var mysql = require("mysql");
var DateUtil = require('../../lib/utils/DateUtil');
var _ = require("underscore");

var connection = require('../../lib/utils/DbconnectUtil');

/**
 * 查询项目列表
 */
router.get('/', function (req, res, next) {
    //console.log("route: /list");
    var queryAudit = 'select * from t_audit';

    connection().query(queryAudit, function (error, results) {
        if (error) {
            res.send({code : -1 , message: JSON.stringify(error)});
        } else {
            res.send({code :0 , data : results});
        }
    });
});

/**
 * 查询项目内容
 */
router.get('/:auditId', function (req, res, next) {
    //console.log("route: /audit");
    var auditId = req.params.auditId;

    var queryAuditSql = 'select * from t_audit where t_audit.id = ? ';
    connection().query(queryAuditSql,[auditId], function (error, results) {
            if (error || results.length == 0) {
                console.log(error);
                res.send({code: -1, message: '查询数据失败'});
            } else {
                res.send({code: 0, data: results[0]});
            }
        });
});

/**
 * 更新项目内容
 */
router.put('/:auditId', function (req, res, next) {
    var audit = req.body;

    connection().query('UPDATE t_audit SET name = ?, type = ?, fileUrl = ? WHERE id = ?',
        [audit.name, audit.type, audit.fileUrl, audit.id], function (err, results) {
            if (err) {
                console.log(err);
                res.send({code: -1, message: '保存数据失败'});
            } else {
                res.send({code: 0, data: audit});
            }
        });
});

/**
 * 更新项目内容
 */
router.post('/', function (req, res, next) {
    var audit = req.body;
    audit.id = new Date().getTime()+ '';
    connection().query('INSERT INTO  t_audit SET id = ?,name = ?, type = ?, fileUrl = ?',
        [ audit.id, audit.name, audit.type, audit.fileUrl], function (err, results) {
            if (err) {
                console.log(err);
                res.send({code: -1, message: '保存数据失败'});
            } else {
                res.send({code: 0, data: audit});
            }
        });
});

/**
 * 删除项目内容
 */
router.delete('/:auditId', function (req, res, next) {
    connection().query('DELETE FROM  t_audit WHERE id = ?', [req.params.auditId], function (err, results) {
        if (err) {
            console.log(err);
            res.send({code: -1, message: '删除数据失败'});
        } else {
            res.send({code: 0, data: results});
        }
    });
});

module.exports = router;